package com.qf.common.interceptor;

import com.qf.entity.sys.SysUser;
import com.qf.exception.CustomerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.qf.utils.RedisUtil;

/**
 * 自定义的登陆拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        // 登录成功后，将token发送给前端
        // 前端发送请求时，需要将token放到请求头中，发送给后台

        // 本例，从Authorization这个请求头中获取token值
        // 注意,需要将前端的请求头改变为Authorization
        String token = request.getHeader("Authorization");
        //StringUtils这个工具类  spring框架提供的
        if(!StringUtils.hasLength(token)) {
            throw new CustomerException("403","请重新登陆");
        }
        SysUser userToken = (SysUser)redisUtil.getCacheObject(token);
        if (userToken == null) {
            throw new CustomerException("403","身份失效,请重新登陆");
        }
        // 放行
        return true;
    }
}
